package com.atguigu.tingshu.handel;

import com.atguigu.tingshu.model.CDCEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * ClassName: UserCdcHandler
 * Package: com.atguigu.tingshu.handel
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/7/30 Wednesday 13:09
 * @Version 1.0
 */
@Slf4j
@Component
//监听表名的变化
@CanalTable("user_info")
public class UserCdcHandler implements EntryHandler<CDCEntity> {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 监听到数据新增操作
     *
     * @param cdcEntity
     */
    @Override
    public void insert(CDCEntity cdcEntity) {
        EntryHandler.super.insert(cdcEntity);
    }

    /**
     * 监听到数据更新操作
     *
     * @param before 变更前的数据
     * @param after  变更后的数据
     */
    @Override
    public void update(CDCEntity before, CDCEntity after) {
        //1.构建用户信息缓存key
        String key = "user:info:" + after.getId();
        //2.删除缓存
        redisTemplate.delete(key);

    }

    /**
     * 监听到数据删除操作
     *
     * @param cdcEntity
     */
    @Override
    public void delete(CDCEntity cdcEntity) {
        //1.构建用户信息缓存key
        String key = "user:info:" + cdcEntity.getId();
        //2.删除缓存
        redisTemplate.delete(key);
    }
}